from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, PyMongoError

# 连接字符串
connection_string = 'mongodb://xkb_prod_backup:xkb_prod_backup@dds-2zec1c50c123cf241234-pub.mongodb.rds.aliyuncs.com:3717'

client = None  # 初始化为 None

try:
    # 尝试连接到 MongoDB
    client = MongoClient(connection_string, serverSelectionTimeoutMS=5000)
    print("成功连接到 MongoDB")

    # 指定数据库
    db_name = 'xkb_prod_backup'
    db = client[db_name]
    print("正在查询数据库:", db_name)

    # 要删除的条件
    delete_condition = {'orderNo': 'J1645045741379'}

    # 删除 orders 集合中的文档
    orders_collection = db['orders']
    delete_result_orders = orders_collection.delete_many(delete_condition)
    print(f"在 'orders' 集合中删除了 {delete_result_orders.deleted_count} 个文档")

    # 删除 ordersDetail 集合中的文档
    orders_detail_collection = db['ordersDetail']
    delete_result_orders_detail = orders_detail_collection.delete_many(delete_condition)
    print(f"在 'ordersDetail' 集合中删除了 {delete_result_orders_detail.deleted_count} 个文档")

except ServerSelectionTimeoutError as e:
    print("连接失败: 服务器选择超时", e)
except PyMongoError as e:
    print("连接失败: PyMongo错误", e)
finally:
    if client is not None:
        client.close()
        print("连接已关闭")